import { Injectable, OnModuleInit } from "@nestjs/common";
import { MongoService } from "./mongo.service";
import dayjs from 'dayjs'
import { RedisService } from "./redis.service";

const WXID_TO_USER_PRIFIX = 'WXID2USER:'

@Injectable()
export class QueryService implements OnModuleInit {

    timestamp: number = 0
    msgs: object[] = []
    lastMsg: string = null

    constructor(
        private mongoService: MongoService,
        private redisService: RedisService
    ) { }

    onModuleInit() {
        // 暂时不用测试环带缓冲
        // setInterval(async () => {
        //     let res = await this.getMessageSinceTime("si_2062181717_8171668571",this.timestamp)

        //     for (const msg of res[0].newests) {
        //         console.log(`${dayjs(msg.Data.MsgSeq).format('YYYY-MM-DD HH:mm:ss.SSS')}`)
        //     }

        //     this.msgs.push(...res[0].newests)

        //     console.log(`最小可读索引${res[0].backIndex}:==>${dayjs(res[0].min.Data.MsgSeq).format('YYYY-MM-DD HH:mm:ss.SSS')}`)
        //     console.log(`最大可读索引${res[0].forwardIndex}:==>${dayjs(res[0].max.Data.MsgSeq).format('YYYY-MM-DD HH:mm:ss.SSS')}`)

        //     if (this.lastMsg) {
        //         console.log(`最后消息:${this.lastMsg}`)
        //     } else {
        //         console.log(`最后消息:[空列表]`)
        //     }

        //     if (!res[0].newests.length) {
        //         console.log('[无最新消息]')
        //         return
        //     }else{
        //         console.log(`收到:[${res[0].newests.length}]条最新消息`)
        //     }

        //     let header = res[0].newests[0] as object
        //     let newest = this.msgs[this.msgs.length - 1] as object

        //     console.log(`起始消息:${dayjs(header['Data']['MsgSeq']).format('YYYY-MM-DD HH:mm:ss.SSS')}`)

        //     this.lastMsg = dayjs(newest['Data']['MsgSeq']).format('YYYY-MM-DD HH:mm:ss.SSS')
        //     this.timestamp = newest['Data']['MsgSeq'] as number

        //     console.log(`最新消息:${this.lastMsg}`)

        // }, 6000)
    }

    // async getWxLatestMessages(Wxid) {
    //     let res = await this.mongoService.msgColl.aggregate([
    //         {
    //             $match: {$regex:`${Wxid}`}
    //         },
    //         {
    //             $project:{}
    //         }
    //     ])
    // }

    async getMessageSinceTime(doc_id:any,timestamp: number) {

        let res = await this.mongoService.msgColl.aggregate([
            {
                $match: { doc_id}
            },
            {
                $project: {
                    _id: 0,
                    newests: {
                        $slice: [{
                            $sortArray: {
                                input: {
                                    $filter: {
                                        input: "$msgs",
                                        as: 'msg',
                                        cond: {
                                            $gt: ['$$msg.Data.MsgSeq', timestamp]
                                        }
                                    },

                                },
                                sortBy: {
                                    "Data.MsgSeq": 1
                                }
                            }
                        }, -10]
                    },
                    // 使用$arrayElemAt获取数组指定索引的元素
                    forwardIndex: {
                        $mod: [{ $subtract: ['$forwardIndex', 1] }, "$maxBufferLen"]
                    },
                    backIndex: 1,
                    max: {
                        $let: {
                            vars: {
                                indexRaw: {
                                    $mod: [{ $subtract: ['$forwardIndex', 1] }, "$maxBufferLen"]
                                }
                            },
                            in: {
                                $arrayElemAt: ["$msgs", "$$indexRaw"] // 获取数组的第一个元素
                                //$multiply : ["$$indexRaw" , 1]
                            }
                        },
                    },
                    min: {
                        $arrayElemAt: ["$msgs", "$backIndex"] // 获取数组的第一个元素
                    }

                }
            }])
            .toArray()

        return res
    }

    async setWxid2UserID(wxid,user_id){
        await this.redisService.redis().set(`${WXID_TO_USER_PRIFIX}${wxid}`,user_id)
    }

    async getUserIDByWxid(wxid) {
        return await this.redisService.redis().get(`${WXID_TO_USER_PRIFIX}${wxid}`)
    }
}